Implicit and Explicit Route Model Binding


1. Implicit Route Model Binding

// Define a route with implicit model binding
Route::get('user/{user}', [UserController::class, 'show'])->name('user.show');

// In UserController
public function show(User $user)
{
    return view('user.show', compact('user'));
}

Route Definition: Route::get('user/{user}', [UserController::class, 'show']) automatically resolves the User model for the {user} parameter using its primary key.

Controller Method: Laravel injects the User model instance directly into the show method, simplifying code and avoiding manual query logic.

2. Explicit Route Model Binding

// Define a route with explicit model binding
Route::get('post/{post}', [PostController::class, 'show'])->name('post.show');

// In AppServiceProvider 
public function boot()
{
    parent::boot();
    Route::bind('post', function ($value) {
        return Post::where('slug', $value)->firstOrFail();
    });
}

// In PostController
public function show(Post $post)
{
    return view('post.show', compact('post'));
}

Route Definition: Route::get('post/{post}', [PostController::class, 'show']) uses explicit binding to handle custom retrieval logic.

Custom Binding Logic: In AppServiceProvider, Route::bind('post', function ($value) { ... }) allows you to define how the model should be resolved, such as using a non-primary key (e.g., slug).

Controller Method: Laravel injects the Post model instance, resolved by the custom logic, into the show method.

Difference

Implicit Binding: Automatically resolves models based on route parameters and primary keys, making code cleaner and easier to maintain.

Explicit Binding: Allows custom logic for model retrieval, offering more flexibility in how models are resolved.

You Might Also Like

Cache Blade Views for Faster Rendering

Cache rendered Blade views to store compiled templates and reduce server processing time. Laravel's...

Use HTTPS for Secure Communication

Ensure your application uses HTTPS to encrypt data transmitted between the client and server. Update...